package com.pason.onlineshop.mainshop.application;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.pason.onlineshop.mainshop.exceptions.ApplicationException;
import com.pason.onlineshop.mainshop.util.EnvironmentUtil;

public class ShopApplication implements InitializingBean {
	
	protected static final Logger logger = LoggerFactory.getLogger(ShopApplication.class);
	
	private static ShopApplication _INSTANCE;
	
	private String SHOP_ROOT_SHARED_FOLDER = "/data/onlineshop/";
	private String DEV_ROOT_PATH_PREFIX = "target";
	private String SHOP_STAGING_FOLDER;
	private String SHOP_PRODUCTION_FOLDER;
	private List<String> productionFolders;
	
	private ShopApplication(){
		SHOP_PRODUCTION_FOLDER = new StringBuilder(SHOP_ROOT_SHARED_FOLDER).append("production").toString();
		SHOP_STAGING_FOLDER = new StringBuilder(SHOP_ROOT_SHARED_FOLDER).append("staging").toString();
		productionFolders = new ArrayList<String>();
		productionFolders.add(SHOP_PRODUCTION_FOLDER);
		productionFolders.add(SHOP_STAGING_FOLDER);
	}
	
	public static ShopApplication getInstance() {
        if (ShopApplication._INSTANCE == null) {
            synchronized (ShopApplication.class) {
                _INSTANCE = new ShopApplication();
            }
        }
        return _INSTANCE;
    }
	
	@Override
	public void afterPropertiesSet() throws Exception {
		//Create NAS folders
		createNasDirectoriesInProduction();
	}
	
	void createNasDirectoriesInProduction() {
        createNasDirectoriesInProduction(productionFolders.toArray(new String[productionFolders.size()]));
    }

    void createNasDirectoriesInProduction(final String[] folders) {
        for (String folderName : folders) {
            File folder = new File(folderName);
            if (!folder.exists()) {
                if (!folder.mkdirs()) {
                    throw new ApplicationException("Unable to create directory " + folder.getAbsolutePath());
                }

            }
        }
    }

	public List<String> getProductionFolders() {
		return productionFolders;
	}
	
	public File getNASRootFolder() {
        return new File(SHOP_PRODUCTION_FOLDER);
    }
	

}
